/*---------------------------------- START base.js ----------------------------------*/
var tm = {};

tm.Main =
{
	init: function()
	{
		$('body').append('<img src="/i/ajax-loader.gif" style="position:absolute; left:-999em; top: -999em;" />');
		
		var stopListWords = ('STOP_LIST_WORDS'.translate()).split(' ');
		$(stopListWords).each(function (i, v) {
			var w = v.toLowerCase().replace([]);
			if (typeof stopListWords[v] == 'undefined') {
				stopListWords[v] = i;
			}
		});
		if (stopListWords && stopListWords instanceof Array && stopListWords.length > 0) {
			tm.Config.stopListWords = stopListWords;
		}
		else {
			tm.Config.stopListWords = [];
		}
		var frms = $('form:visible');
		if(frms.length > 0)
		{
			frms.each( function() { $(':input', this).focus( function() { this.hasFocus = true; } ).blur( function() { this.hasFocus = false; } ); } );
			//$(':input:visible:enabled', frms[0]).not($(':radio,:checkbox', frms[0])).get(0).focus();
		}
		Date.format = tm.Config.dateFormat;
	},
	getParam: function(name)
	{
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var tmpURL = window.location.href;
		var results = regex.exec( tmpURL );
		if( results === null ) {
			return "";
		} else {
			return results[1];
		}
	},
	pageName: function()
	{
		return window.location.href.replace(/^(.+[\/\\])([^\/\\\?]+)(\?.+)?$/, '$2');
	}
};

tm.String =
{
	translate: function(params)
	{
		if(tm.l18n && tm.l18n[this])
		{
			var str = tm.l18n[this], re;
			if(params)
			{
				for(param in params)
				{
					re = new RegExp('%' + param + '%', 'g');
					str = str.replace(re, params[param]);
				}
			}
			return str;
		}
		else
		{
			return this;
		}
	},
	escapeHTML: function()
	{
		return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g, '&quot;');
	  },
	unescapeHTML: function()
	{
		return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
	},
	countWords: function(simple)
	{
		if (typeof simple == 'undefined' || simple !== true) {
			simple = false;
		}
		var re1 = /[\.,:;\?\!\s\t\n\r]+/i;
		var re2 = /[-�_\s\t\n\r,\.:;\?\!"'`\(\)\[\]\{\}]+$/i;
		var words = this.split(re1);
		var wordsCounter = 0;
		$(words).each(function () {
			var word = this.replace(re2, '');
				if (simple && word.length > 0) {
					wordsCounter++;
				} else if (word.length > 2 && typeof tm.Config.stopListWords[word.toLowerCase()] == 'undefined') {
					wordsCounter++;
				}
		});
		return wordsCounter;
	},
	base64_encode: function()
	{
		var ks = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var s = '';
		var c1, c2, c3 = '';
		var e1, e2, e3, e4 = '';
		var i = 0;
		do
		{
			c1 = this.charCodeAt(i++);
			c2 = this.charCodeAt(i++);
			c3 = this.charCodeAt(i++);
			e1 = c1 >> 2;
			e2 = ((c1 & 3) << 4) | (c2 >> 4);
			e3 = ((c2 & 15) << 2) | (c3 >> 6);
			e4 = c3 & 63;
			if (isNaN(c2))
			{
				e3 = e4 = 64;
			}
			else if (isNaN(c3))
			{
				e4 = 64;
			}
			s = s + ks.charAt(e1) + ks.charAt(e2) + ks.charAt(e3) + ks.charAt(e4);
			c1 = c2 = c3 = e1 = e2 = e3 = e4 = "";
		}
		while (i < this.length);
		return s;
	},
	base64_decode: function()
	{
		var ks = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var s = "";
		var c1, c2, c3 = "";
		var e1, e2, e3, e4 = "";
		var i = 0;
		var re = /[^A-Za-z0-9\+\/\=]/g;
		if ( re.exec(this) )
		{
			return this;
		}
		var cs = this.replace(re, '');
		do
		{
			e1 = ks.indexOf(cs.charAt(i++));
			e2 = ks.indexOf(cs.charAt(i++));
			e3 = ks.indexOf(cs.charAt(i++));
			e4 = ks.indexOf(cs.charAt(i++));
			c1 = (e1 << 2) | (e2 >> 4);
			c2 = ((e2 & 15) << 4) | (e3 >> 2);
			c3 = ((e3 & 3) << 6) | e4;
			s = s + String.fromCharCode(c1);
			if (e3 != 64)
			{
				s = s + String.fromCharCode(c2);
			}
			if (e4 != 64)
			{
				s = s + String.fromCharCode(c3);
			}
			c1 = c2 = c3 = e1 = e2 = e3 = e4 = "";
		}
		while (i < cs.length);
		return s;
	}
};

tm.Array =
{
	indexOf: function(val)
	{
		var index = -1;
		$(this).each
		(
			function(i, n)
			{
				if(n == val && index == -1)
				{
					index = i;
				}
			}
		);
		return index;
	}
};

String.prototype.translate = tm.String.translate;
String.prototype.escapeHTML = tm.String.escapeHTML;
String.prototype.unescapeHTML = tm.String.unescapeHTML;
String.prototype.countWords = tm.String.countWords;
String.prototype.base64_encode = tm.String.base64_encode;
String.prototype.base64_decode = tm.String.base64_decode;
Array.prototype.indexOf = tm.Array.indexOf;

$(tm.Main.init);

tm.b64 =
{
	init: function()
	{
		$('span.b64').each(function() {
			$(this).html($(this).html().base64_decode());
		});
		$('a[class=b64]').each(function() {
			$(this).attr('href',$(this).attr('href').base64_decode());
		});
	}
};

$(tm.b64.init);

tm.ErrorMessage =
{
	alert: function(errors)
	{
		var message = 'ERR_FRM_HDR'.translate() + '\n\n';
		for(var i = 0; i < errors.length; i++)
		{
			message += '   - ' + errors[i] + ';' + '\n';
		}
		message += '\n' + 'ERR_FRM_FTR'.translate();
		alert(message);
	}
};

$(function () {
	var dateMin;
	if ($('input[type="hidden"]#dateMin').length > 0)
	{
		var v = $('input[type="hidden"]#dateMin').val();
		dateMin = Date.fromString(v);
	}

	tm.SearchForms.currentForm = $('#frm-hotel-search, #frm-car-search, #frm-package-search-params, #frm-air');
	$('.date-picker').each (
		function () {
			var $this = $(this);
			$this.datepicker({
				showOn: 'button',
				duration: '',
				speed: '',
				numberOfMonths: 2,
				prevText: '&#x3c;&#x3c;',
				nextText: '&#x3e;&#x3e;',
				currentText: 'CURRENT_TEXT'.translate(),
				firstDay: 1,
				changeFirstDay: false,
				dayNamesMin: ['DOW_SHORT_SUN'.translate(),'DOW_SHORT_MON'.translate(),'DOW_SHORT_TUE'.translate(),'DOW_SHORT_WED'.translate(),'DOW_SHORT_THI'.translate(),'DOW_SHORT_FRI'.translate(),'DOW_SHORT_SAT'.translate()],
				monthNames: ['MONTH_LONG_JAN'.translate(), 'MONTH_LONG_FEB'.translate(), 'MONTH_LONG_MAR'.translate(), 'MONTH_LONG_APR'.translate(), 'MONTH_LONG_MAY'.translate(), 'MONTH_LONG_JUN'.translate(), 'MONTH_LONG_JUL'.translate(), 'MONTH_LONG_AUG'.translate(), 'MONTH_LONG_SEP'.translate(), 'MONTH_LONG_OCT'.translate(), 'MONTH_LONG_NOV'.translate(), 'MONTH_LONG_DEC'.translate()],
				buttonImage: '/i/calendar.gif',
				buttonImageOnly: true,
				buttonText: 'CALENDAR'.translate(),
				dateFormat: 'dd.mm.yy',
				displayClose: true,
				displayCurrent: true,
				closeText: 'x',
				onClose: function() {
					if ($.browser.msie && $.browser.version.number < 7) {
						$('div.form_search_outer select').css('visibility', 'visible');
					}
				}
			});

			if (tm.SearchForms.currentForm.length > 0)
			{
				var currDatePicker = $(this, tm.SearchForms.currentForm);
				if (currDatePicker.length > 0)
				{
					var currDate = new Date();
					var min, sel = currDatePicker.val();
					min = dateMin;
					switch (this.id)
					{
						case 'depdate':
							if (sel == '')
							{
								sel = currDate.addDays(14).asString();
							}

						break;
						case 'enddate':
							var depDate = $('input#depdate').val();
							if (sel == '')
							{
								sel = currDate.addDays(21).asString();
								min = $(this).parents('form').attr('id') == 'frm-car-search' ? Date.fromString(sel) : Date.fromString(sel).addDays(1);
							}
							if (depDate != '')
							{
								min = $(this).parents('form').attr('id') == 'frm-car-search' ? Date.fromString(depDate) : Date.fromString(depDate).addDays(1);
							}
						break;
					}
					currDatePicker.datepicker('change', {
						'onSelect': tm.SearchForms.dateSelected2,
						'minDate': '' + min
					});

					tm.SearchForms.dates[this.id] = sel;
					currDatePicker.val(sel);
				}
			}
		}
	);

	$('#hotel_search_outer ul.hotel-rating li a.star').each(function() {
		var $this = $(this);
		var chkd = false;
		$this.each(function() {
			$this = $(this);
			if ($(this).parents('li').find('input').attr('checked')) {
				chkd = true;
			}
			if (chkd) {
				$this.parent(0).addClass('active');
			}
			$(this).mousedown(function(e) {
				$this = $(this);
				$this.siblings('input').trigger('click');
				var activesLength = $this.parents('.hotel-rating').find('li.active').length;
				if (chkd && (activesLength > 1)) {
					$this.parent(0).removeClass('active');
					chkd = false;
				} else {
					$this.parent(0).addClass('active');
					chkd = true;
				}
			});
		});
	});

	if ($.browser.msie && $.browser.version.number < 7) {
		$('.datepicker_trigger').click(function() {
			if ($('div.datepicker_multi').is(':visible')) {
				$(this).parents('div.form_search_outer').find('div.col-2 select, div.col-3 select').css('visibility', 'hidden');
			}
		});
	}

	$('input.date-picker').click(function() {
	   $(this).siblings('img.datepicker_trigger').triggerHandler('click');
	});
});

tm.Dates =
{
	getMonthesOptions: function(monthes, selectedMonth)
	{
		var res = '';
		for(i = 0; i < monthes.length; i++)
		{
			res += '<option value="' + (i+1) + '"' + ((selectedMonth > 0 && selectedMonth <= monthes.length && selectedMonth == i + 1) ? (' selected="selected"') : ('')) + '>' + monthes[i]+ '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	getDaysOptions: function(selectedDay)
	{
		var res = '';
		for(i = 1, l = 31; i <= l; i++)
		{
			res += '<option value="' + i + '"' + ((selectedDay > 0 && selectedDay <= l && selectedDay == i) ? (' selected="selected"') : ('')) + '>' + ((i < 10) ? ('0') : ('')) + i + '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	getYearsOptions: function(selectedYear)
	{
		var res = '';
		var curDate = new Date();
		for(i = curDate.getFullYear(), l = curDate.getFullYear() - 100; i >= l; i--)
		{
			res += '<option value="' + i + '"' + ((selectedYear > 0 && selectedYear <= curDate.getFullYear() && selectedYear == i) ? (' selected="selected"') : ('')) + '>' + i + '&nbsp;&nbsp;</option>';
		}
		return res;
	},
	/**
	 * Compares two dates
	 *
	 * Returns:
	 *   if date1 less then date2: -1
	 *   if date1 and date2 are same: 0
	 *   if date1 more than date2: 1
	 *
	 * NOTE: in comparision now used ONLY day, month and year!
	 */
	compare: function(date1, date2)
	{
		var d1, d2;
		if (typeof date1 == 'string') d1 = Date.fromString(date1)
		else d1 = date1;
		if (typeof date2 == 'string') d2 = Date.fromString(date2)
		else d2 = date2;

		d1 = d1.valueOf();
		d2 = d2.valueOf();

		if (d1 < d2) return -1;
		if (d1 == d2) return 0;
		return 1;
	}
};

tm.FormControls = {
	radio: null,
	init: function () {
		if (!$.browser.msie || ($.browser.msie && $.browser.version.number > 5.5)) {
			$(':checkbox').each(function () { tm.FormControls.replaceCheckbox(this); });
			$(':radio').each(function () {
				tm.FormControls.addRadioButtonGroup(this);
				tm.FormControls.replaceRadioButton(this);
			});
		}
	},
	addRadioButtonGroup: function(rbtn) {
		if (tm.FormControls.radio === null) {
		   tm.FormControls.radio = {};
		}
		var rbtnName = $(rbtn).attr('name').replace(/(\[|\])+/ig, '_');
		if(rbtnName && rbtnName.length > 0 && typeof tm.FormControls.radio[rbtnName] == 'undefined') {
			tm.FormControls.radio[rbtnName] = 0;
		}
	},
	replaceCheckbox: function(chkbox) {
		// d/ebugger;
		var chk = $(chkbox);
		if (chk.siblings('a#chk_' + chk.attr('id')).length == 0)
		{
			chk.after('<a href="#checkbox" id="chk_' + chk.attr('id') + '" class="tm-checkbox"><img src="' + tm.Config.imgsPath + 'b.gif" alt="Checkbox" width="14" height="20"' + (chkbox.checked ? ' class="checked"' : '') + ' /></a>');
			chk.css( { position: 'absolute', top: '-10000px' } );
			chk.next().click( function() {  return tm.FormControls.checkboxClick(this); } ).keydown(tm.FormControls.onButtonsKeyDown);
			$('label[for=' + chk.attr('id') + ']').click( function() { return tm.FormControls.checkboxClick($('#' + this.htmlFor).next()); } );
		}
	},
	replaceRadioButton: function(rdbtn) {
		if (rdbtn.checked)
		{
			var rdbtnName = $(rdbtn).attr('name').replace(/(\[|\])+/ig, '_');
			tm.FormControls.radio[rdbtnName] = rdbtn;
		}
		var rdbtnId = '';
		if ($(rdbtn).attr('id') && $(rdbtn).attr('id').length > 0) {
			rdbtnId = ' id="rdbId_' + $(rdbtn).attr('id') + '"';
		}
		$(rdbtn).after('<a href="#radiobutton"' + rdbtnId + ' class="tm-radiobutton"><img src="' + tm.Config.imgsPath + 'b.gif" alt="Radiobutton" width="14" height="20"' + (rdbtn.checked ? ' class="checked"' : '') + ' /></a>');
		$(rdbtn).css({'position': 'absolute', 'top': '-10000px'});
		$(rdbtn).next().click( function() {  return tm.FormControls.radioButtonClick(this); } ).keydown(tm.FormControls.onButtonsKeyDown);
		$('label[for=' + $(rdbtn).attr('id') + ']').click( function() { return tm.FormControls.radioButtonClick($('#' + this.htmlFor).next()); } );
	},
	onButtonsKeyDown: function(event)
	{
		switch(event.keyCode)
		{
			case 32:
				$(this).click();
				break;
		}
	},
	checkboxClick: function(lnk)
	{
		$('img', lnk).toggleClass('checked');
		$(lnk).prev().get(0).click();
		return false;
	},
	radioButtonClick: function(lnk)
	{
		var btn = $(lnk).prev();
		if (!btn.attr('checked')) {
			var btnName = btn.attr('name').replace(/(\[|\])+/ig, '_');

			/*
			btn.parents('form').find(':radio[name="' + btnName + '"]:checked').removeAttr('checked').next('a.tm-radiobutton').children('img').removeClass('checked');
			$(lnk).children('img').toggleClass('checked');
			btn.attr('checked', 'checked').trigger('click');
			*/

			if(tm.FormControls.radio[btnName] !== 0)
			{
				$(tm.FormControls.radio[btnName]).removeAttr('checked').next('a.tm-radiobutton').children('img').removeClass('checked');
			}
			tm.FormControls.radio[btnName] = btn.get(0);
			$(lnk).children('img').toggleClass('checked');
			btn.attr('checked', 'checked').trigger('click');

		}
		return false;
	}
};
$(tm.FormControls.init);

tm.SearchForms =
{
	dates: {},
	currentForm: null,
	timer: null,
	init: function()
	{
		var frm = $('#frm-hotel-search, #frm-car-search');
		if (tm.SearchForms.currentForm === null && frm.length > 0)
		{
			tm.SearchForms.currentForm = frm;
		}
		if(!$.browser.msie || ($.browser.msie && $.browser.version.number > 5.5))
		{
			if(tm.SearchForms.currentForm && tm.SearchForms.currentForm.length > 0)
			{
				$('input[type=text],input[type=hidden],input[type=checkbox],input[type=radio],select', tm.SearchForms.currentForm.get(0)).each
				(
					function()
					{
						if(this.nodeName.toLowerCase() != 'input' || (this.type && (this.type.toLowerCase() != 'checkbox' && this.type.toLowerCase() != 'radio')))
						{
							if(this.nodeName.toLowerCase() == 'select')
							{
								$(this).bind
								(
									'change',
									tm.SearchForms.onFormChange
								);
							}
						}
						else
						{
							$(this).bind
							(
								'click',
								tm.SearchForms.onFormChange
							);
						}
					}
				);
				tm.SearchForms.currentForm.submit
				(
					function()
					{
						$('input[type=hidden]:disabled', tm.SearchForms.currentForm).remove();
						return true;
					}
				);
			}
		}
	},
	onFormChange: function(e)
	{
		var elm = $(this);
		var elmId = elm.attr('id');

		$('.date-picker').blur();

	},

	dateSelected2: function(selectedDate, datePicker)
	{
		tm.SearchForms.dates[this.id] = selectedDate;
		if (this.id == 'depdate' && $("input#enddate").length > 0)
		{
			var enddate = $("input#enddate");
			var date = Date.fromString(selectedDate);

			$('div.form_search_outer').parents('form').attr('id') == 'frm-car-search' ? date : date.addDays(1);
			var cmpDates = tm.Dates.compare(date, tm.SearchForms.dates.enddate) > 0;
			if (enddate.val() == '' || cmpDates)
			{
				var strDate = date.asString();
				if (cmpDates)
				{
					tm.SearchForms.dates.enddate = strDate;
				}
				enddate.val(tm.SearchForms.dates.enddate);
			}

			//enddate.datepicker('change', {'minDate': Date.fromString(selectedDate).addDays(1)});
			enddate.datepicker('change', {'minDate': '' + date});
		}
		else if (this.id == 'enddate')
		{
			var depdate = $("input#depdate");

			var cmpDates = tm.Dates.compare(tm.SearchForms.dates.depdate, selectedDate) > 0;
			if (cmpDates)
			{
				tm.SearchForms.dates.depdate = $('input[type="hidden"]#dateMin').val();
			}
			if (depdate.val() == '')
			{
				$(this).datepicker('change', {'minDate': '' + Date.fromString(tm.SearchForms.dates.depdate).addDays(1)});
				depdate.val(tm.SearchForms.dates.depdate);
			}
		}

		//$('div#cnt-top div.tabs ul.menu li.active a').focus();

		tm.SearchForms.currentForm.get(0).dataChanged = true;
		tm.SearchForms.onFormChange(this);
	}
};

$(tm.SearchForms.init);

tm.Tips =
{
	init: function()
	{
		if(!$.browser.msie || ($.browser.msie && $.browser.version.number > 5.5))
		{
			$('.tip').each
			(
				function()
				{
					tm.Tips.tipInit(this);
				}
			);
		}
	},
	tipInit: function(tip)
	{
		var elm = $(tip);
		var temp = elm.html();
		elm.html('<div class="tcnt"><table><tr><td class="tl"><img src="' + tm.Config.imgsPath + 'b.gif" alt="" width="10" height="10" /></td><td class="tm"><img src="' + tm.Config.imgsPath + 'b.gif" width="1" height="1" alt="" /></td><td class="tr"><img src="' + tm.Config.imgsPath + 'b.gif" alt="" width="10" height="10" /></td></tr><tr><td class="ml"><img src="' + tm.Config.imgsPath + 'b.gif" width="1" height="1" alt="" /></td><td class="mm"><div class="out">' + temp + '</div></td><td class="mr"><img src="' + tm.Config.imgsPath + 'b.gif" width="1" height="1" alt="" /></td></tr><tr><td class="bl"><img src="' + tm.Config.imgsPath + 'b.gif" alt="" width="10" height="10" /></td><td class="bm"><img src="' + tm.Config.imgsPath + 'b.gif" width="1" height="1" alt="" /></td><td class="br"><img src="' + tm.Config.imgsPath + 'b.gif" alt="" width="10" height="10" /></td></tr></table><div class="tail">&nbsp;</div></div>');
		elm.removeClass('tip-generic');
	}
};

$(tm.Tips.init);

tm.Popup =
{
	types:
	[
		'signin',
		'edit-logo',
		'simple-request',
		'image',
		'wait-screen',
		'content',
		'simple-html',
		'cancel-conditions',
		'flights-avail-check'
	],
	images: [],
	objects: [],
	prefix: '<div id="popupWindow"><table id="popupCommon"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c"><div class="hdr"><a href="#close-popup" class="close" title="%close%"><span>%close%</span></a><h2>%header%</h2></div><div class="cnt clear-after">',
	postfix: '</div><div class="ftr clear-after"><a href="#ok" class="ok" title="%ok%"><span>%ok%</span></a><a href="#cancel" class="cancel" title="%cancel%"><span>%cancel%</span></a></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>',
	postfixImage: '</div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>',
	popupTimer: null,
	clickedElm: null,
	metaData: null,
	popupImagesPreload: function()
	{
		var images =
		[
			'overlays/trans.png',
			'loading-long.gif',
			'b.gif',
			'overlays/login/png/t.png',
			'overlays/login/png/b.png',
			'overlays/login/png/l.png',
			'overlays/login/png/r.png',
			'overlays/login/hdr-bg.gif',
			'overlays/login/bg-t.gif',
			'overlays/login/bg-b.jpg',
			'overlays/login/close.gif',
			'overlays/login/close-over.gif',
			'overlays/common/png/t.png',
			'overlays/common/png/rt.png',
			'overlays/common/png/r.png',
			'overlays/common/png/rb.png',
			'overlays/common/png/b.png',
			'overlays/common/png/lb.png',
			'overlays/common/png/l.png',
			'overlays/common/png/lt.png',
			'overlays/common/close.gif',
			'overlays/common/close-over.gif',
			'controls/checkbox-signin.gif',
		];
		for(i = 0; i < images.length; i++)
		{
			tm.Popup.images[i] = new Image();
			tm.Popup.images[i].src = tm.Config.imgsPath + images[i];
		}
	},
	popupFlashPreload: function()
	{
		var objects =
		[
			'ajax-loader.swf'
		];
		for(i = 0; i < objects.length; i++)
		{
			tm.Popup.objects[i] = new Object();
			tm.Popup.objects[i].path = tm.Config.imgsPath + objects[i];
		}
	},
	popupImagesPreloaded: function()
	{
		var allImagesLoaded = true;
		imagesLoop: for(i = 0; i < tm.Popup.images.length; i++)
		{
			if(typeof tm.Popup.images[i].complete == 'undefined')
			{
				break imagesLoop;
			}
			if(tm.Popup.images[i].complete == false)
			{
				allImagesLoaded = false;
				break imagesLoop;
			}
		}
		return allImagesLoaded;
	},
	popupObjectsPreloaded: function()
	{
		var allObjectsLoaded = false;
		
		if ($('#popupWindow #ajaxLoaderFlash').html() != '') {
			allObjectsLoaded = true;
		}
				
		return allObjectsLoaded;
	},
	init: function()
	{
		if(!$.browser.msie || ($.browser.msie && $.browser.version.number > 5.5))
		{
			if(tm.Popup.images.length == 0)
			{
				tm.Popup.popupImagesPreload();
			}
			if (tm.Popup.objects.length == 0) {
				tm.Popup.popupFlashPreload();
			}
			$(window).unbind('resize').unbind('scroll');
			$('.popup').each
			(
				function()
				{
					tm.Popup.popupInit(this);
				}
			);
		}
	},
	unbind: function()
	{
		$('.popup').unbind(tm.Popup.clickEvent);
	},
	clickEvent: function(e)
	{
		e.preventDefault();
		tm.Popup.formSubmit(this);
		tm.Popup.popupClick(this);
	},
	popupInit: function(elm)
	{
		$(elm).click(tm.Popup.clickEvent);
	},
	formSubmit: function(elm)
	{
		if (!$(elm).hasClass('popup-no-submit')) {
//			alert(tm.Popup.popupObjectsPreloaded());
			if (tm.Popup.popupObjectsPreloaded()) {
				$(elm).parents('form').submit();
			} else {
				$('.popup').each
				(
					function()
					{
						tm.Popup.popupInit(this);
					}
				);
			}
		}
		return false;
	},
	popupClick: function(elm)
	{
		tm.Popup.idx = $('a.popup.image').index(elm);
		tm.Popup.clickedElm = elm;
		//tm.Popup.unbind();
		$('#root').after('<div id="popupOverlay"></div>');
		$('#popupOverlay').click
		(
			function(e)
			{
				e.stopPropagation();
				tm.Popup.popupClose();
			}
		);
		$('#popupOverlay').after('<div id="popupLoading"></div>');
		if($.browser.msie && $.browser.version.number < 7) {
			$('#popupOverlay').css( 'height', Math.max(parseInt($(window).height()), parseInt($(document).height()), (parseInt($(document.documentElement).height()) - 4)) + 'px' );
		}
		if($.browser.opera && $.browser.version.number < 9) {
			$('#popupOverlay').css('background', 'transparent url(' + tm.Config.imgsPath + 'overlays/trans.png) fixed');
		}
		if($.browser.msie && $.browser.version.number < 7) {
			$('#popupOverlay').bgiframe();
//            $('#popupLoading').css('top', Math.round($(window).height()/2 - 7 + $(window).scrollTop()) + 'px');
		}
		tm.Popup.popupShow();
	},
	popupShow: function()
	{
		var classNames = $(tm.Popup.clickedElm).attr('class').split(' ');
		outerLoop:
		for(i = 0; i < classNames.length; i++)
		{
			for(o = 0; o < tm.Popup.types.length; o++)
			{
				if(classNames[i] == tm.Popup.types[o])
				{
					tm.Popup.popupOfTypeShow(classNames[i]);
					break outerLoop;
				}
			}
		}
	},
	popupOfTypeShow: function(type)
	{
		tm.Popup.popupType = type;
		$('#popupLoading').css({
			display:    'block',
			zIndex:     '199',
			opacity:    1
		});
		var prefix, postfix, content;
		switch(type)
		{
			case 'simple-request':
				prefix = ((tm.Popup.prefix).replace(/%header%/gi, ($(tm.Popup.clickedElm).metadata()).header)).replace(/%close%/gi, 'BTN_CLOSE'.translate());
				postfix = ((tm.Popup.postfix).replace(/%ok%/gi, 'BTN_OK'.translate())).replace(/%cancel%/gi, 'BTN_CANCEL'.translate());
				break;
			case 'image':
				var imageTitle = $(tm.Popup.clickedElm).metadata().title;
				if (imageTitle !== null && typeof imageTitle != 'undefined' && imageTitle.length > 0) {
					imageTitle = imageTitle.escapeHTML();
				}
				else
				{
					imageTitle = 'LBL_PHOTO_UNTITLED'.translate();
				}
				prefix = ((tm.Popup.prefix).replace(/%header%/gi, imageTitle)).replace(/%close%/gi, 'BTN_CLOSE'.translate());
				postfix = tm.Popup.postfixImage;
				break;
			case 'wait-screen':
				prefix = '<div id="popupWindow"><table id="popupCommon"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c"><div class="hdr"><h2>' + 'HDR_POPUP_SEARCH_WAIT_SCREEN_HEADER'.translate() + '</h2></div><div class="cnt clear-after">';
				postfix = '</div><div class="ftr clear-after"></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>';
				break;
			case 'content':
				var prefix = '<div id="popupWindow"><table id="popupCommon"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c ' + $(tm.Popup.clickedElm).metadata().className + '"><div class="hdr"><a class="close" title="' + 'BTN_CLOSE'.translate() +'" href="#close-popup"><span>' + 'BTN_CLOSE'.translate() +'</span></a><h2>' + $(tm.Popup.clickedElm).metadata().header + '</h2></div><div class="cnt clear-after">';
				var postfix = '</div><div class="ftr clear-after"></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>';
				var thisContent = '<div id="player"></div>';
				var content = prefix + thisContent + postfix;
				$('#popupLoading').after(content);
				var so = new SWFObject('/misc/js/lib/mediaplayer/player.swf','mpl','640','480','9');
				so.useExpressInstall('/misc/js/lib/mediaplayer/expressInstall.swf');
				so.addParam('allowscriptaccess','always');
				so.addParam('allowfullscreen','true');
				so.addParam('flashvars','&description=Коммерческое предложение для турагенств и туроператоров от Тревел Меню.&file=/misc/video/travelmenu.flv&backcolor=#F9F2E3&screencolor=#F9F2E3&abouttext=' + $(tm.Popup.clickedElm).metadata().abouttext + '&aboutlink=' + $(tm.Popup.clickedElm).metadata().aboutlink);
				so.write('player');
				$('#popupCommon a.close').click(function() {
					tm.Popup.popupClose();
					return false;
				});
				tm.Popup.popupEscClose();
				break;
		}

		switch(type)
		{
			case 'signin':
				/*var domain = window.location.hostname.match(/^((www\.)?(.+))$/i);
				var base = tm.Config.BaseDomain.match(/^(http(s)?:\/\/)((www\.)?(.+))(:[0-9]+)?(\/)?$/i);*/
				var returnUrl = tm.Popup.clickedElm.href;
				/*if (domain[3].toLowerCase() != base[5].toLowerCase())
				{
					var re = new RegExp( base[5].toLowerCase().replace(/\./, '\\.').replace(/\//, '\\/') );
					returnUrl = returnUrl.replace(re, domain[3].toLowerCase());
					returnUrl = returnUrl.replace(/www\./, '');
				}*/

				if ($(tm.Popup.clickedElm).hasClass('order-button')) {
					var
						$link = $(tm.Popup.clickedElm),
						ids = [], roomIndexes = [], transferIndex,
						availForm = $link.parents('form.propositions'),
						d_propos = availForm.find('div.d_propositions'),
						currentUrl = location.href
					;
					d_propos.find('div.room_choose').each(function() {
						roomIndexes.push($(this).find('input[type="radio"]:checked').val());
					});
					if (d_propos.find('div.transfer_choose').length > 0) {
						transferIndex = d_propos.find('div.transfer_choose input[type="radio"]:checked').val();
						returnUrl += 'transfer_index=' + transferIndex;
					}/* else {
						transferIndex = -1;
					}*/
/*					returnUrl += 'transfer_index=' + transferIndex;*/
					for (var i = 0; i < roomIndexes.length; i++) {
						returnUrl += '&room_index[' + i + ']=' + roomIndexes[i];
					}
					
					availCode = availForm.find('span.hotel-avail-code').text();
/*					availCode = availForm.find('input[name="avail_code"]').val();*/
					if (availCode) {
						returnUrl += '&avail_code=' + availCode;
					}
					
					//var continueUrl = returnUrl; // allow registration along with order
					if($('#header-cart-info').text().length > 0)
					{
						document.location = returnUrl;
						return;
					}
				} else if ($(tm.Popup.clickedElm).hasClass('order-button-air')) {
					var thisForm = $(tm.Popup.clickedElm).parents('form');
					returnUrl += 'itineraryCode=' + thisForm.children('input.itineraryCodeMain').val() + '&flightIndex0=' + thisForm.children('input.flightIndex0Main').val() + '&flightIndex1=' + thisForm.children('input.flightIndex1Main').val() + '&flightIndex2=' + thisForm.children('input.flightIndex2Main').val();
					if($('#header-cart-info').text().length > 0)
					{
						document.location = returnUrl;
						return;
					}
				}
				var continueUrl = returnUrl;
				registerUrl = '/a_registration';

				var content = '<div id="popupWindow"><table id="popupSignin"><tr><td colspan="3" class="top"><div><a href="#close-popup" title="' + 'BTN_CLOSE'.translate() + '"><img src="' + tm.Config.imgsPath + 'b.gif" width="21" height="24" alt="' + 'BTN_CLOSE'.translate() + '" /></a></div></td></tr>' + 
				//'<tr><th class="left"><div></div></th><th class="middle"><h1><strong>' + 'I_HAVE_NO_ACCOUNT'.translate() + '</strong><span>' + 'HDR_MEMBERSHIP_CARD'.translate() + '</span></h1></th><th class="right"><div></div></th></tr>' +
				'<tr id="no-account-holder"><td class="left"><div></div></td><td class="middle">' + 
				'<div id="no-account">' + 'I_HAVE_NO_ACCOUNT'.translate() + '<div class="links"><p><a class="continueUrl" href="' + continueUrl + '">' + 'LNK_CONTINUE_WITHOUT_REGISTERING'.translate() + '</a></p><p><a tabindex="1006" href="' + registerUrl + '">' + 'LNK_REGISTER'.translate() +'</a></p></div></div>' +
				'</td></tr>' +
				'<tr><th class="left"><div></div></th><th class="middle"><h1><strong>' + 'HDR_POPUP_SIGNIN'.translate() + '</strong><span>' + 'HDR_MEMBERSHIP_CARD'.translate() + '</span></h1></th><th class="right"><div></div></th></tr><tr><td class="left"><div></div></td><td class="middle"><div class="content"><form action="/a_login.login" method="post" id="frm-si"><table> <!--tr><td colspan="3">&nbsp;</td></tr--><!--tr class="popup-error"><td>&nbsp;</td><td colspan="2" class="msg">Ut non velit. Nullam nec sem at odio pretium facilisis. Sed malesuada.</td></tr--> <tr><td class="lbl"><label for="frm-si-email">' + 'LBL_EMAIL'.translate() + ':&nbsp;</label></td><td class="fld"><input tabindex="1001" type="text" name="email" id="frm-si-email" maxlength="255" /></td><td class="hlp">&nbsp;</td></tr> <!--tr class="popup-error"><td>&nbsp;</td><td colspan="2" class="msg">Curabitur turpis tellus, bibendum lacinia, eleifend et, lacinia eget, massa. Nunc sit.</td></tr--> <tr><td class="lbl"><label for="frm-si-password">' + 'LBL_PASSWORD'.translate() + ':&nbsp;</label></td><td class="fld"><input tabindex="1002" type="password" name="password" id="frm-si-password" maxlength="255" /></td><td class="hlp"><a tabindex="1005" href="/a_forgotpass" class="{name: \'popupForm\'}" title="' + 'LNK_FORGOT_PASSWORD'.translate() + '">' + 'LNK_FORGOT_PASSWORD'.translate() + '</a></td></tr><tr class="chkbx"><td class="lbl">&nbsp;</td><td class="fld"><table><tr><td><input type="checkbox" name="remember" value="1" id="frm-si-remember" /></td><td><label for="frm-si-remember">' + 'LBL_REMEMBER_ME'.translate() + '</label></td></tr></table></td><td class="hlp">&nbsp;</td></tr><tr class="sbmt"><td class="lbl">&nbsp;</td><td class="fld"><input tabindex="1003" type="image" id="frm-si-submit" src="' + tm.Config.imgsPath + 'buttons/login.gif" /> &nbsp;' + 'OR'.translate() + '&nbsp;<a tabindex="1004" href="#close-popup">' + 'BTN_CANCEL'.translate() + '</a></td><td class="hlp">&nbsp;</td></tr></table><input type="hidden" name="current_url" value="' + currentUrl + '" /><input type="hidden" name="redirect" value="' + continueUrl + '" /><input type="hidden" name="action" value="signin" /></form>' + 
				'</div></td><td class="right"><div></div></td></tr><tr><td colspan="3" class="bottom"><div></div></td></tr></table></div>';
				$('#popupLoading').after(content);
				if ($(tm.Popup.clickedElm).hasClass('order-button') || $(tm.Popup.clickedElm).hasClass('order-button-air')) {
					$('#no-account-holder').show();
				}
				$('#popupWindow input[type="text"]:first').focus();
				tm.ForgotPassword.init();
				$('#popupSignin td.top a, #popupSignin table .sbmt .fld a').click
				(
					function()
					{
						tm.ForgotPassword.unbindPopup();
						tm.Popup.popupClose();
						return false;
					}
				);
				break;
			case 'edit-logo':
				req = {
					'redirect' : window.location.href
				};
				$.ajax({
					async    : false,
					type     : "GET",
					url      : "/a_ajax/customization.getEditLogoContent",
					dataType : "json",
					data     : req,
					success: function(resp) {
						if (!resp.error) {
							$('#popupLoading').after(resp.data);
						}
						else {
							alert(resp.error);
						}
					}
				});
				inputFileOver();
				bindLogoEvents();
				$('#popupEditLogo .handler-logo-back').click(function(){
					tm.Popup.popupClose();
					return false;
				});
				break;
			case 'simple-request':
				content = prefix + postfix;
				$('#popupLoading').after(content);
				tm.SimpleRequest.init();
				$('#popupCommon a.cancel').remove();
				$('#popupCommon a.close, #popupCommon a.cancel').click
				(
					function()
					{
						tm.Popup.popupClose();
						return false;
					}
				);
				break;
			case 'image':
				content = prefix + postfix;
				$('#popupLoading').after(content);
				tm.PopupImage.init();
				$('#popupCommon a.cancel').remove();
				$('#popupCommon .m .m .c').addClass('popupWithImage');
				$('#popupCommon a.close, #popupCommon a.cancel').click(function() {
					tm.Popup.popupClose();
					return false;
				});
				tm.Popup.popupEscClose();
				break;
			case 'wait-screen':
				var thisContent;
				thisContent = '<span id="ajaxLoaderFlash"><img id="ajaxLoaderGif" src="/i/ajax-loader.gif" width="42" height="42" alt="" /></span>';
				content = prefix + thisContent + '<span class="search_wait_text">' + $(tm.Popup.clickedElm).metadata().text + '</span>' + postfix;
				$('#popupLoading').after(content);

				if ($(tm.Popup.clickedElm).parents('#mapm').length <= 0) {
					var so = new SWFObject("/misc/i/ajax-loader.swf","mymovie","42","42","7");
					so.addParam("wmode", "transparent");
					so.write("ajaxLoaderFlash");
				}
				
				$('#popupCommon .search_wait_text span').hide();
				$('#popupCommon .search_wait_text span:first').show();
				function waitScreenTextAnimate() {
					setTimeout(function() {
						var timer = setTimeout(waitScreenTextAnimate, 5000);
						var it = $('#popupCommon .search_wait_text span:visible');
						if (it.next('span').length > 0) {
							it.hide();
							it.next('span').fadeIn();
						} else {
							it.hide();
							$('#popupCommon .search_wait_text span:first').fadeIn();
						}
					}, 5000);
				}
				waitScreenTextAnimate();
				$('#popupOverlay').unbind();
				$('#payment-data-collector').submit();
				break;
			case 'simple-html':
				prefix = '<div id="popupWindow"><table id="popupCommon" class="popupSimpleHTML"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c ' + $(tm.Popup.clickedElm).metadata().className + '"><div class="hdr"><a class="close" title="' + 'BTN_CLOSE'.translate() +'" href="#close-popup"><span>' + 'BTN_CLOSE'.translate() +'</span></a><h2>' + $(tm.Popup.clickedElm).metadata().header + '</h2></div><div class="cnt clear-after">';
				postfix = '</div><div class="ftr clear-after"></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>';
				thisContent = '<div id="popup_simple_html">' + $(tm.Popup.clickedElm).next('.popup-simple-html-text').html() + '</div>';
				var content = prefix + thisContent + postfix;
				$('#popupLoading').after(content);

				$('#popupCommon a.close').click(function() {
					tm.Popup.popupClose();
					return false;
				});
				break;
			case 'cancel-conditions':
				prefix = '<div id="popupWindow"><table id="popupCommon" class="popupSimpleHTML"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c"><div class="hdr"><a class="close" title="' + 'BTN_CLOSE'.translate() +'" href="#close-popup"><span>' + 'BTN_CLOSE'.translate() +'</span></a><h2>' + $(tm.Popup.clickedElm).metadata().header + '</h2></div><div class="cnt clear-after">';
				postfix = '</div><div class="ftr clear-after"></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>';
				thisContent = '<span id="ajaxLoaderFlash"><img id="ajaxLoaderGif" src="/i/ajax-loader.gif" width="42" height="42" alt="" /></span>';
				var content = prefix + thisContent + '<span class="search_wait_text">' + 'RECIEVING_DATA'.translate() + '</span>' + postfix;
				$('#popupLoading').after(content);

				var so = new SWFObject("/misc/i/ajax-loader.swf","mymovie","42","42","7");
				so.addParam("wmode", "transparent");
				so.write("ajaxLoaderFlash");

				$('#popupCommon a.close').click(function() {
					tm.Popup.popupClose();
					return false;
				});
				
				var ajaxURL, ajaxData;
				if ($(tm.Popup.clickedElm).hasClass('air-cancel-conditions')) {
					ajaxURL = '/a_search/air.getCancelConditions';
					ajaxData = {itineraryCode: $(tm.Popup.clickedElm).metadata().itineraryCode};
				} else if ($(tm.Popup.clickedElm).hasClass('hotel-cancel-conditions')) {
					
					var
						$link = $(tm.Popup.clickedElm),
						ids = [], roomIndexes = [], transferIndex,
						availForm = $link.parents('form.propositions'),
						d_propos = availForm.find('div.d_propositions'),
						transferIndex = '',
						returnUrl = ''
					;
					d_propos.find('div.room_choose').each(function() {
						roomIndexes.push($(this).find('input[type="radio"]:checked').val());
					});
					if (d_propos.find('div.transfer_choose').length > 0) {
						transferIndex = d_propos.find('div.transfer_choose input[type="radio"]:checked').val();
						returnUrl += 'transfer_index=' + transferIndex;
					}
					for (var i = 0; i < roomIndexes.length; i++) {
						returnUrl += '&room_index[' + i + ']=' + roomIndexes[i];
					}
/*					availCode = availForm.find('input[name="avail_code"]').val();*/
					availCode = availForm.find('span.hotel-avail-code').text();
					if (availCode) {
						returnUrl += '&avail_code=' + availCode;
					}
					ajaxURL = '/a_cart/hotel.getCancelConditions?' + returnUrl;
					ajaxData = {};
				}
				var cnt = $('#popupWindow .c .cnt');
				setTimeout(function() {
					$.ajax({
						url: ajaxURL,
						method: 'post',
						timeout: 20000,
						dataType: 'json',
						data: ajaxData,
						success: function(data){
							if(data.status != undefined && data.status == 'success' && data.data.cancelConditions != '') {
								data = data.data;
								cnt.html('<div id="popup_simple_html">' + data.cancelConditions + '</div>');
							} else {
								cnt.html('<div class="alerted">' + 'ERROR_ORDER_RESPONSE_TEXT'.translate() + ' <a href="javascript: tm.Popup.popupClose();">' + 'BTN_CLOSE'.translate() + '</a></div>');
							}
							tm.Popup.windowResize();
						},
						error: function(){
							cnt.html('<div class="alerted">' + 'ERROR_ORDER_RESPONSE_TEXT'.translate() + ' <a href="javascript: tm.Popup.popupClose();">' + 'BTN_CLOSE'.translate() + '</a></div>');
							tm.Popup.windowResize();
						}
					});
				}, 10);
				break;
			case 'flights-avail-check':
				prefix = '<div id="popupWindow"><table id="popupCommon"><tr class="t"><td class="l"><div class="c"></div></td><td class="m"><div class="c"></div></td><td class="r"><div class="c"></div></td></tr><tr class="m"><td class="l"><div class="c"></div></td><td class="m"><div class="c"><div class="hdr"><h2>' + 'CHECKING_OUT'.translate() + '</h2></div><div class="cnt clear-after">';
				postfix = '</div><div class="ftr clear-after"></div></div></td><td class="r"><div class="c"></div></td></tr><tr class="b"><td class="l" class="c"><div class="c"></div></td><td class="m" class="c"><div class="c"></div></td><td class="r" class="c"><div class="c"></div></td></tr></table></div>';
				var thisContent = '<span id="ajaxLoaderFlash"></span> <div class="waitingMessage">' + 'FLIGHTS_AVAIL_CHECK_MSG'.translate() + '</div>';
				var content = prefix + thisContent + postfix;
				$('#popupLoading').after(content);
				
				var so = new SWFObject("/misc/i/ajax-loader.swf","mymovie","42","42","7");
				so.addParam("wmode", "transparent");
				so.write("ajaxLoaderFlash");
				
				tm.Popup.windowResize();
				
				$('#popupCommon a.close').click(function() {
					tm.Popup.popupClose();
					return false;
				});
				var form = $(tm.Popup.clickedElm).parents('form');
				$.ajax({
					url: '/a_cart/air.checkAvail',
					method: 'post',
					timeout: 20000,
					dataType: 'json',
					data: {
						itineraryCode: form.find('input.itineraryCodeMain').val(),
						flightIndex0: form.find('input.flightIndex0Main').val(),
						flightIndex1: form.find('input.flightIndex1Main').val(),
						flightIndex2: form.find('input.flightIndex2Main').val()
					},
					success: function(data) {
						if (data) {
							if ($(tm.Popup.clickedElm).metadata().isLogged == 'true') {
								form.submit();
							} else {
								$('#popupOverlay').remove();
								$('#popupWindow').remove();
								$(tm.Popup.clickedElm).removeClass('flights-avail-check').addClass('signin').trigger('click');
							}
						} else {
							$('#popupWindow .c .cnt').html('<div>' + 'NOT_AVAIL_FLIGHT_TICKETS'.translate() + ' <a href="javascript: tm.Popup.popupClose();">' + 'RETURN_TO_FLIGHT_CHOOSE'.translate() + '</a></div>');
						}
					},
					error: function() {
						$('#popupWindow .c .cnt').html('<div class="alerted">' + 'CANNOT_GET_DATA_TRY_LATER'.translate() + '<br /><a href="javascript: tm.Popup.popupClose();">' + 'RETURN_TO_FLIGHT_CHOOSE'.translate() + '</a></div>');
					}
				});
				
				break;
		}
		if(!$.browser.msie || $.browser.version.number >= 7) {
			if ($.browser.opera) {
				$('#popupWindow').css('top', (Math.round(self.innerHeight/2-$('#popupWindow').height()/2)) + 'px');
			} else {
				$('#popupWindow').css('top', (Math.round($(window).height()/2-$('#popupWindow').height()/2)) + 'px');
			}
		} else {
//			$('#popupWindow').css('top', (Math.round(document.documentElement.clientHeight / 2 - $('#popupWindow').height() / 2) + 'px'));
			$('#popupWindow').css('top', (document.documentElement['clientHeight'] / 2 - $('#popupWindow').height() / 2 + $(window).scrollTop() + 'px'));
			$(window).scroll( function() {
				tm.Popup.windowScroll();
				$('#popupLoading').css('top', (document.documentElement['clientHeight'] / 2 - $('#popupLoading').height() / 2 + $(window).scrollTop() + 'px'));
				$('#popupWindow').css('top', (document.documentElement['clientHeight'] / 2 - $('#popupWindow').height() / 2 + $(window).scrollTop() + 'px'));
			});
		}
		$(window).resize( function() { tm.Popup.windowResize(); } );
		$('#popupWindow input[type=checkbox]').each( function() { tm.FormControls.replaceCheckbox(this); } );
		$('#popupWindow input[type=radio]').each( function() { tm.FormControls.replaceRadioButton(this); } );
		var controls = $('body,#popupWindow input,#popupWindow select,#popupWindow textarea,#popupWindow button');
		//controls.bind('keypress', function(event) { tm.Popup.popupKeypress(event); } );
		tm.Popup.popupLoaded();
	},
	popupKeypress: function(event)
	{
		switch(event.keyCode)
		{
			case 27:
				if ($('#popupWindow table').attr('id') != 'popupCommon') {
					tm.Popup.popupClose();
				}
				break;
			case 13:
				// In login popup enter is bineded and overwrites autoselect
				var nodeName = event.target.nodeName.toLowerCase();
				if(nodeName != 'textarea')
				{
				   $('#popupWindow a.ok,#frm-si-submit').click();
				}
				break;
		}
	},
	popupLoaded: function()
	{
		if(tm.Popup.popupImagesPreloaded()) {
			$('#popupLoading').remove();
			$('#popupWindow').css('visibility', 'visible');
			var firstElementFocused = false;
			$('#popupWindow input, #popupWindow textarea, #popupWindow select').each(function() {
				if(!this.disabled && !firstElementFocused) {
					$(this).focus();
					firstElementFocused = true;
				}
			});
		} else {
			tm.Popup.popupTimer = window.setTimeout('tm.Popup.popupLoaded()', 100);
		}
	},
	windowResize: function()
	{
		if(!$.browser.msie || $.browser.version.number >= 7) {
			if ($.browser.opera) {
				$('#popupWindow').css('top', (Math.round(self.innerHeight/2-$('#popupWindow').height()/2)) + 'px');
			} else {
				$('#popupWindow').css('top', (Math.round($(window).height() / 2 - $('#popupWindow').height() / 2) + 'px'));
			}
		} else {
			$('#popupWindow').css('top', (Math.round(document.documentElement['clientHeight'] / 2 - $('#popupWindow').height() / 2 + $(window).scrollTop()) + 'px'));
			$('#popupLoading').css('top', (Math.round(document.documentElement['clientHeight'] / 2 - 7 + $(window).scrollTop()) + 'px'));
		}
	},
	windowScroll: function()
	{
		if (!$.browser.msie || ($.browser.msie && $.browser.version.number > 6)) {
			$('#popupWindow').css('top', (Math.round($(window).height() / 2 - $('#popupWindow').height() / 2 + $(window).scrollTop()) + 'px'));
			$('#popupLoading').css('top', (Math.round($(window).height() / 2 - 7 + $(window).scrollTop()) + 'px'));
		}
		if ($.browser.msie && $.browser.version.number == 6) {
			$('select').css('visibility', 'hidden');
		}
	},
	popupClose: function()
	{
		if ($.browser.msie && $.browser.version.number == 6) {
			$('select').css('visibility', 'visible');
		}
		$('#popupLoading, #popupWindow, #popupOverlay').css('visibility','hidden');
		$('#popupLoading').remove();
		tm.Popup.clickedElm = tm.Popup.popupType = null;
		window.setTimeout('tm.Popup.popupClean()', 100);
	},
	popupEscClose: function()
	{
		$(document).bind('keyup', function(event) {
			switch(event.keyCode) {
				case 27:
					tm.Popup.popupClose();
					break;
			}
			return false;
		});
	},
	popupClean: function()
	{
		$('#popupOverlay, #popupLoading, #popupWindow, #popupOverlay *, #popupLoading *, #popupWindow *').unbind();
		$(window).unbind('scroll').unbind('resize');
		$('body').unbind();
		$('#popupWindow,#popupLoading,#popupOverlay').remove();
		tm.Popup.init();
	}
};

$(tm.Popup.init);

tm.SimpleRequest =
{
	content: null,
	successContent: null,
	failedContent: null,
	init: function()
	{
		this.content = $(tm.Popup.clickedElm).metadata().content.unescapeHTML();
		this.successContent = $(tm.Popup.clickedElm).metadata().successContent.unescapeHTML();
		this.failedContent = $(tm.Popup.clickedElm).metadata().failedContent.unescapeHTML();
		$('#popupCommon .m .m .cnt').html(this.content).css('width', ($(tm.Popup.clickedElm).metadata().width + 'px'));
		$('#popupCommon .m .m .ftr a.cancel').hide();
		$('#popupCommon .m .m .ftr a.ok').addClass('disabled').click(tm.SimpleRequest.okClicked);
		$('#popupCommon .m .m .ftr').addClass('loading');
		tm.SimpleRequest.sendRequest();
	},
	okClicked: function(event)
	{
		event.preventDefault();
		if(this.className.search(/disable/) == -1)
		{
			tm.Popup.popupClose();
		}
		return false;
	},
	sendRequest: function()
	{
		$.ajax
		(
			 {
				async:        false,
				type:        "GET",
				url:         $(tm.Popup.clickedElm).metadata().ajaxURL,
				dataType:    "json",
				timeout:    30000,
				success:    function(data)
				{
					tm.SimpleRequest.onRequestSuccess(data);
				},
				error:        function(request, settings, exeption)
				{
					tm.SimpleRequest.onRequestError(request, settings, exeption);
				}
			}
		);
		return;
	},
	onRequestSuccess: function(data)
	{
		if(data == 0)
		{
			$('#popupCommon .m .m .cnt').html(this.failedContent);
		}
		else
		{
			$('#popupCommon .m .m .cnt').html(this.successContent);
		}
		$('#popupCommon .m .m .ftr a.ok').removeClass('disabled');
		$('#popupCommon .m .m .ftr').removeClass('loading');

	},
	onRequestError: function(request, settings, exeption)
	{
		$('#popupCommon .m .m .cnt').html('<p>' + 'ERR_AJAX_NO_RESPONSE'.translate().replace(/\n/ig, '<br />') + '</p>');
		$('#popupCommon .m .m .ftr a.ok').removeClass('disabled');
		$('#popupCommon .m .m .ftr').removeClass('loading');
		return;
	}
};

tm.PopupImage = {
	content: null,
	image: null,
	timer: null,
	imgs: [],
	sWidth: [],
	sHeight: [],
	sTitle: [],
	init: function (idx) {
		var images =
		[
			'popup/arrow-l.png',
			'popup/arrow-r.png',
			'popup/arrow-l-hover.png',
			'popup/arrow-r-hover.png',
			'popup/arrow-l-disabled.png',
			'popup/arrow-r-disabled.png'
		];
		for(i = 0; i < images.length; i++) {
			tm.Popup.images[i] = new Image();
			tm.Popup.images[i].src = tm.Config.imgsPath + images[i];
		}

		var i, j=0;
		$('a.popup.image').each(function(e) {
			tm.PopupImage.imgs.push(this);
			tm.PopupImage.sWidth.push($(this).metadata().srcwidth);
			tm.PopupImage.sHeight.push($(this).metadata().srcheight);
			tm.PopupImage.sTitle.push($(this).metadata().title);
		});

		tm.PopupImage.content = '<div class="popupImage"><a href="javascript:void(0)" class="control prev-photo" title="' + 'PREVIOUS'.translate() + '"></a>' +
		'<img src="' + $(tm.Popup.clickedElm).attr('href') + '" width="' + ($(tm.Popup.clickedElm).metadata()).srcwidth + '" height="' + ($(tm.Popup.clickedElm).metadata()).srcheight + '" alt="" />' +
		'<a href="javascript:void(0)" class="control next-photo" title="' + 'NEXT'.translate() + '"></a></div>';
		$('#popupCommon .m .m .cnt').html(tm.PopupImage.content);

		var cTop = (($(tm.Popup.clickedElm).metadata()).srcheight - 32)/2 + 3 + 'px';
		$('div.popupImage a.control').css('top', cTop);

		/*
		$('#popupCommon .m .m .cnt').css({
			width: (($(tm.Popup.clickedElm).metadata().width+6) + 'px'),
			height: (($(tm.Popup.clickedElm).metadata().height+6) + 'px')
		});
		*/
		tm.PopupImage.image = $('#popupCommon div.popupImage img');
		tm.PopupImage.timer = window.setTimeout(tm.PopupImage.checkLoading, 100);
		tm.PopupImage.controls();
	},
	controls: function() {
		var ais = $('a.popup.image').size();
		if (tm.Popup.idx == 0) {
			$('div.popupImage a.prev-photo').addClass('prev-photo-disabled');
		}
		if (tm.Popup.idx == ais-1) {
			$('div.popupImage a.next-photo').addClass('next-photo-disabled');
		}
		var imgChange = function() {
			$('div.popupImage img').attr({
				src:       '',
				width:     tm.PopupImage.sWidth[tm.Popup.idx],
				height:    tm.PopupImage.sHeight[tm.Popup.idx]
			}).css({
				width:     tm.PopupImage.sWidth[tm.Popup.idx] + 'px',
				height:    tm.PopupImage.sHeight[tm.Popup.idx] + 'px'
			});
			setTimeout(function() {
				$('div.popupImage img').attr({
					src:    tm.PopupImage.imgs[tm.Popup.idx]
				});
				$('div.popupImage img').parents('.popupWithImage').find('h2').html(tm.PopupImage.sTitle[tm.Popup.idx]);
				tm.PopupImage.controlsPosition();
			}, 100);
			$('div.popupImage img').load(function() {
				$(this).css('visibility', 'visible');
			});
			tm.Popup.windowResize();
		}
		var prevClick = function() {
			$('div.popupImage img').css('visibility', 'hidden');
			if (tm.Popup.idx < ais-1) {
				$('div.popupImage a.next-photo').removeClass('next-photo-disabled');
				bindNextClick();
			}
			if (tm.Popup.idx > 0) {
				tm.Popup.idx--;
				imgChange();
				$(this).parents('.popupWithImage').find('h2').html(tm.PopupImage.sTitle[tm.Popup.idx]);
				$('div.popupImage a.next-photo').removeClass('next-photo-disabled');
				bindNextClick();
				if (tm.Popup.idx == 0) {
					$('body').unbind('keydown', prevKeypress);
					$('div.popupImage a.prev-photo').addClass('prev-photo-disabled').unbind('click', prevClick);
				}
			}
			tm.Popup.windowResize();
		}

		var nextClick = function() {
			$('div.popupImage img').css('visibility', 'hidden');
			if (tm.Popup.idx > 0) {
				$('div.popupImage a.prev-photo').removeClass('prev-photo-disabled');
				bindPrevClick();
			}
			if (tm.Popup.idx < ais-1) {
				tm.Popup.idx++;
				imgChange();
				$('div.popupImage a.prev-photo').removeClass('prev-photo-disabled');
				bindPrevClick();
				if (tm.Popup.idx == ais-1) {
					$('body').unbind('keydown', nextKeypress);
					$('div.popupImage a.next-photo').addClass('next-photo-disabled').unbind('click', nextClick);
				}
			}
			tm.Popup.windowResize();
		}

		var prevKeypress = function(event) {
			switch(event.keyCode) {
				case 37:
					prevClick();
					break;
			}
		}

		var nextKeypress = function(event) {
			switch(event.keyCode) {
				case 39:
					nextClick();
					break;
			}
		}

		var bindPrevClick = function() {
			$('div.popupImage a.prev-photo').bind('click', prevClick);
			$('body').bind('keydown', prevKeypress);
		}
		var bindNextClick = function() {
			$('div.popupImage a.next-photo').bind('click', nextClick);
			$('body').bind('keydown', nextKeypress);
		}
		if (tm.Popup.idx != 0) {
			bindPrevClick();
		}
		if (tm.Popup.idx != ais-1) {
			bindNextClick();
		}

	},
	controlsPosition: function() {
		var cTop = ($('div.popupImage').height() - 32)/2 + 3 + 'px';
		$('div.popupImage a.control').css('top', cTop);
	},
	checkLoading: function () {
		if(tm.PopupImage.image && tm.PopupImage.image.length > 0) {
			if(typeof tm.PopupImage.image.get(0).complete != 'undefined' && !tm.PopupImage.image.get(0).complete) {
				tm.PopupImage.timer = window.setTimeout(tm.PopupImage.checkLoading, 100);
			}
			else {
				tm.PopupImage.image.css('visibility','inherit');
			}
		}
		tm.Popup.windowResize();
	}
};

tm.ForgotPassword =
{
	links: {
		loginForm: false,
		popupForm: false
	},
	init: function()
	{
		$('a[href="/a_forgotpass"]').each(function()
		{
			var data = $(this).metadata();

			if (typeof data.name == 'string')
			{
				switch (data.name)
				{
					case 'loginForm':
						if (! tm.ForgotPassword.links.loginForm)
						{
							tm.ForgotPassword.links.loginForm = true;
						}
					break;

					case 'popupForm':
						if (! tm.ForgotPassword.links.popupForm)
						{
							tm.ForgotPassword.links.popupForm = true;
						}
					break;
				}

				$(this).click(tm.ForgotPassword.onClick);
			}
		});
	},
	unbindPopup: function()
	{
		tm.ForgotPassword.links.popupForm = false;
	},
	onClick: function()
	{
		var frm = $('div#popupWindow form#frm-si');

		if (! frm.length)
		{
			frm = $('form#frm-signup');
		}
		frm = frm.get(0);

		this.href += (frm.email.value) ? '?email=' + encodeURIComponent(frm.email.value) : '';

		return true;
	}
}

$(tm.ForgotPassword.init);

/* index page redirect mechanizm to correct cys section end */

tm.Admin =
{
	languages: [],
	faqCategories: [],
	availableLocations: [],
	init: function()
	{
		var lngSelect = $('#adminLanguageSelect');
		var faqCategorySelect = $('#adminFAQcategorySelect');
		var availableLocationSelect = $('#availableLocationSelect');

		if (lngSelect.length)
		{
			var lngSelector = lngSelect.get(0);

			for (var i = 0; i < lngSelector.options.length; i++)
			{
				tm.Admin.languages[i] = lngSelector.options[i].value;
			}

			lngSelect.change(tm.Admin.changeDocumentLanguage);
		}
		if (faqCategorySelect.length)
		{
			var faqCategorySelector = faqCategorySelect.get(0);

			for (var i = 0; i < faqCategorySelector.options.length; i++)
			{
				tm.Admin.faqCategories[i] = faqCategorySelector.options[i].value;
			}

			faqCategorySelect.change(tm.Admin.changeFAQcategory);
		}
		if (availableLocationSelect.length)
		{
			var aLocationSelector = availableLocationSelect.get(0);

			for (var i = 0; i < aLocationSelector.options.length; i++)
			{
				tm.Admin.availableLocations[i] = aLocationSelector.options[i].value;
			}

			availableLocationSelect.change(tm.Admin.changeLocation);
		}
	},
	/* changing language when editing documents */
	changeDocumentLanguage: function()
	{
		if (tm.Admin.languages.length > 0)
		{
			var url = window.location.href;
			for (var i = 0; i < tm.Admin.languages.length; i++)
			{
				if (this.value == tm.Admin.languages[i])
				{
//					url = url.replace(/[&\?]lng=[a-zA-Z]+/, '') + '&lng=' + tm.Admin.languages[i];
					if (url.search(/[&\?]lng=/) < 0)
					{
						var sign = '&';
						if (url.search(/[\?]/) < 0)
						{
							sign = '?';
						}
						url = url + sign + 'lng=' + tm.Admin.languages[i];
					}
					else
					{
						url = url.replace(/([&\?]lng=)([a-zA-Z]+)?/, '$1' + tm.Admin.languages[i]);
					}
					window.location.href = url;
				}
			}
		}
	},
	/* changing FAQ category */
	changeFAQcategory: function()
	{
		if (tm.Admin.faqCategories.length > 0)
		{
			var url = window.location.href;
			for (var i = 0; i < tm.Admin.faqCategories.length; i++)
			{
				if (this.value == tm.Admin.faqCategories[i])
				{
//					url = url.replace(/([&\?]cat=)\d+/, '$1') + tm.Admin.faqCategories[i];
					if (url.search(/[&\?]cat=/) < 0)
					{
						var sign = '&';
						if (url.search(/[\?]/) < 0)
						{
							sign = '?';
						}
						url = url + sign + 'cat=' + tm.Admin.faqCategories[i];
					}
					else
					{
						url = url.replace(/([&\?]cat=)(\d+)?/, '$1' + tm.Admin.faqCategories[i]);
					}
					window.location.href = url;
				}
			}
		}
	},
	/* changing location */
	changeLocation: function()
	{
		if (tm.Admin.availableLocations.length > 0)
		{
			var url = window.location.href;
			for (var i = 0; i < tm.Admin.availableLocations.length; i++)
			{
				if (this.value == tm.Admin.availableLocations[i])
				{
					if (url.search(/[&\?]location=/) < 0)
					{
						var sign = '&';
						if (url.search(/[\?]/) < 0)
						{
							sign = '?';
						}
						url = url + sign + 'location=' + tm.Admin.availableLocations[i];
					}
					else
					{
						url = url.replace(/([&\?]location=)([a-z]+)?/, '$1' + tm.Admin.availableLocations[i]);
					}
					window.location.href = url;
				}
			}
		}
	}
}

$(tm.Admin.init);

tm.Settings =
{
	markEdit: null,
	init: function()
	{
		tm.Settings.markEdit = $('#markup');
		var mark = $('#markupOn');
		if (tm.Settings.markEdit.length == 1 && mark.length == 1)
		{
			mark.click(function() {
				var val = '';
				if (this.checked) {
					val = '';
				} else {
					val = 'disabled';
				}
				tm.Settings.markEdit.attr('disabled', val);
			});
		}

		$(document.forms['formMarkup']).submit( function()
		{
			tm.Settings.markEdit.removeAttr('disabled');
		});
	}
}
$(tm.Settings.init);

tm.Icq =
{
	icq_timeout: [],
	init: function()
	{
		$('.icq-chat').mouseover(function() {
			$(this).children('a').hide();
			var i = $(this).children('span.icq_number');
			var v = i.val();
			if(tm.Icq.icq_timeout[v]) {
				clearTimeout(tm.Icq.icq_timeout[v]);
			}
			//i.show();
			i.css('display', 'block');
		});
		var f = function(v){
			var i = $('.icq-chat').children('span.icq_number[title=' + v + ']');
			i.hide();
			i.parent().children('a').show();
		};
		$('.icq-chat').mouseout(function() {
			var v = $(this).children('span.icq_number').text();
			f(v);
			//tm.Icq.icq_timeout[v] = setTimeout(function(){f(v)}, 2000);
		});
	}
}
$(tm.Icq.init);

/* Registration form inputs focus event */
$(function() {
	bindBorderSetter();
});

function bindBorderSetter() {
	var focusBorder = function (elm) {
		$(elm).focus(function() {
			$('select').css('border', '1px solid #D6C6BB');
			$(this).css('border', '1px solid #DDAC7B');
		});
		$(elm).blur(function() {
			$(this).css('border', '1px solid #D6C6BB');
		});
		$(elm).find('option').click(function() {
			$(elm).css('border', '1px solid #D6C6BB');
		});
	}
	$('input[type="text"], input[type="password"], select, textarea').each(function() {
		$(this).css('border', '1px solid #D6C6BB');
		focusBorder(this);
	});
};

$(function() {
	bindLightBox();
});

/* Lightbox */
function bindLightBox() {
// $('.layout-container form.editable .content img').each(function() {
	$('form.editable div.content img').each(function() {
		if ($(this).parent(0).tagName != 'a') {
			var src = this.src;
			var fileName = src.substr(0, src.lastIndexOf('.'));
			var fileExt = src.substr(fileName.length + 1);
			var href = fileName + '_full.' + fileExt;
			$(this).wrap('<a href="' + href + '"></a>');
		}
		$(this).parents('a').lightBox({imageBtnClose: '/i/lightbox/lightbox-btn-close.gif', imageLoading: '/i/lightbox/lightbox-ico-loading.gif'});
	});
}

/* Search form */
function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
$(function() {

	if ($.browser.msie) {

		var setAbsolute = function(elm) {
			elm.css('position', 'absolute').parents('.row').css('marginBottom', '11px');
		};
		var setStatic = function(elm) {
			elm.css('position', 'static').parents('.row').css('marginBottom', '8px');
		};

		// Car search
		var w = 80;
		$('#car_search_outer div.col-3 select').mouseover(function() {
			$(this).focus();
			$(this).width('auto');
			setAbsolute($(this));
		}).blur(function() {
			$(this).width(w + 'px');
			setStatic($(this));
		});
		$('#car_search_outer div.col-3 select option').mousedown(function() {
			$(this).parents(0).width(w + 'px');
			setStatic($(this).parents(0));
		}).mouseout(function() {
			$(this).parents(0).width(w + 'px');
			setStatic($(this).parents(0));
		});
	}

});

// Partner site
$(function() {
	$('.editable .controls .lc h2 input').parent(0).hide();
	$('.editable .controls .rc').each(function() {
		if ($(this).find('a').length <= 0 && $(this).siblings('.lc').find('h2:first input').val() <= 0) {
			$(this).parents('.controls').hide();
		}
	});
});

// Check for cookies enabled and browser
$(function() {
	if(!navigator.cookieEnabled) {
		$('#root').prepend('<div id="global-error">' + 'COOKIES_DISABLED'.translate() + '</div>');
	}
	if($.browser.msie && $.browser.version.number < 6) {
		$('#root').prepend('<div id="global-error">' + 'UPDATE_BROWSER'.translate() + '</div>');
	}
});
/*---------------------------------- END base.js ----------------------------------*/